<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>公共聊天室-lianchua</title>

    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询（media queries）功能 -->
    <!-- 警告：通过 file:// 协议（就是直接将 html 页面拖拽到浏览器中）访问页面时 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
    <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->
<!--    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>-->
<!--    <script src="js/jquery-3.2.1.min.js"></script>-->
    <link type="text/css" rel="styleSheet" href="css/index.css"/>
</head>
<body>

<div class="container">
    <h1>在线公共聊天室</h1>
    <ul class="nav nav-pills">
        <li class="active"><a href="#">Home</a></li>
        <li><a href="#">SVN</a></li>
        <li><a href="#">iOS</a></li>
        <li><a href="#">VB.Net</a></li>
        <li><a href="#">Java</a></li>
        <li><a href="#">PHP</a></li>
    </ul>
    <pre id="fit1" class="hide container choose"></pre>
    <textarea id="message_content" readonly="readonly" cols="57" rows="10" class="container choose" onpropertychange="this.style.height=this.scrollHeight + 'px'" oninput="this.style.height=this.scrollHeight + 'px'" onkeypress="if(event.keyCode==13) return false;">

</textarea>

    <br/>

    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title">
                1.加入或退出聊天室
            </h3>
        </div>
        <div class="panel-body">
            <label for="in_user_name">用户姓名 </label>
            <input id="in_user_name" value="" autofocus="autofocus"/>
            <button id="btn_join" class="btn btn-primary">加入聊天室</button>
            <button id="btn_exit" class="btn btn-danger">离开聊天室</button>
            <button type="button" class="btn btn-default" data-toggle="tooltip"  title="默认的 Tooltip"> Enter加入</button>
            <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="左侧的 Tooltip">ESC退出
            </button>
            <button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="顶部的 Tooltip">Enter发送
            </button>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title">
                2.进入公开的聊天室
            </h3>
        </div>
        <div class="panel-body">
            <label for="in_room_msg">群发消息 </label>
            <textarea id="in_room_msg" value="" class="form-control" rows="3" οnkeydοwn="if(event.keyCode==32||event.keyCode==13){return false;}"></textarea>
            <button id="btn_send_all" class="btn btn-success">回车发送</button>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title">
                3.私聊
            </h3>
        </div>
        <div class="panel-body">
            <label for="in_sender">发送者 </label><input id="in_sender" value=""/> <b>to</b>
            <label for="in_receive">接受者 </label><input id="in_receive" value=""/><br/>
            <label for="in_point_message">消息体 </label>

            <textarea id="in_point_message" value="" class="form-control" rows="3" value=""></textarea>
            <button id="btn_send_point" class="btn btn-success">发送消息</button>
        </div>
    </div>
</div>

<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
</body>

<script type="text/javascript">
    $(document).ready(function () {
        var flag = true;
        var log  = false;
        var type = false;
        var urlPrefix = 'ws://172.16.10.1:8080/chat-room/';
        var ws = null;
        $('#btn_join').click(function () {
            if (flag) {
                var username = $('#in_user_name').val();
                localStorage.setItem("username",username);
                console.log("username存入本地缓存");
                var url = urlPrefix + username;
                ws = new WebSocket(url);
                ws.onopen = function () {
                    flag = false;
                    console.log("建立 websocket 连接...");
                };
                $("#in_room_msg").focus();
                ws.onmessage = function (event) {
                    //服务端发送的消息
                    $('#message_content').append(event.data + '');
                    document.getElementById('message_content').scrollTop = document.getElementById('message_content').scrollHeight;
                    console.log("客户端接收服务端数据");
                };

            }
            ws.onclose = function () {
                flag = true;
                var name = localStorage.getItem("username");
                $('#message_content').append('用户[' + name + '] 已经离开聊天室!\n');
                console.log("关闭 websocket 连接...");
                localStorage.clear();
                console.log("清除本地缓存！")
            }

        });
        //客户端群发消息到服务器
        $('#btn_send_all').click(function () {
            var msg = $('#in_room_msg').val();
            //替换文本内的首尾换行符
            msg=msg.replace(/^\n+|\n+$/g,"");
            //获取截取后的文本字符串长度
            var len= msg.toString().length;
            console.log(msg);
            console.log(len);
            var index = msg.indexOf("\n");
            console.log(index);
            //如果包含换行符
            if (msg.indexOf("")===-1) {
                //方法结束
                console.log("end")
            }else{
                console.log("go");
                if (ws&&len!==0) {
                    ws.send(msg);
                    console.log("发送消息到服务端");
                    log = true;
                    document.getElementById("in_room_msg").value = "";
                    console.log("清除群聊输入框的文本");

                }
            }


        });
        // 退出聊天室
        $('#btn_exit').click(function () {
            if (ws) {
                if(window.confirm('你确定要断开连接吗？')){
                    //alert("确定");
                    ws.close();
                }else{
                    //alert("取消");
                    return false;
                }

            }
        });
        //艾特式发消息
        $("#btn_send_point").click(function () {
            var sender = $("#in_sender").val();
            var receive = $("#in_receive").val();
            var message = $("#in_point_message").val();
            $.get("/chat-room/" + sender + "/to/" + receive + "?message=" + message, function () {
                alert("发送成功...")
                console.log("私发消息");
                console.log(message);
                $('#message_content').append('用户[' + sender + '] 对'+'用户['+receive+']'+'说：'+message+'!\n');
            })
        })
        //绑定按钮到按键事件
        document.onkeydown = function (event) {
            var e = event || window.event;
            var keyCode = e.keyCode || e.which;
            if (localStorage.getItem("username")==null){
                switch (keyCode) {
                    case 13:
                        alert("你正在加入聊天室！");
                        $("#btn_join").click();
                        break;
                    case 27:
                        alert("未进入聊天室无法退出！");
                        break;
                    default:
                        break;
                }
            } else {
                console.log(localStorage.getItem("username"));
                switch (keyCode) {
                    case 13:
                        $("#btn_send_all").click();
                        if (log!==true){
                            alert("连接异常，你可能需要重新登录！")
                            localStorage.clear();
                        }
                        break;
                    case 27:
                        alert("触发esc键退出聊天室");
                        $("#btn_exit").click();
                        break;
                    default:
                        break;
                }
            }
        }
    })


</script>

</html>